package com.jiawei.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author : willian fu
 * @date : 2019/12/12
 */
public class TokenUtil {

    /**
     * 从redis中获取userId
     *
     * @param redisTemplate
     * @param header        token头
     * @return
     */
    public static Long getUserIdByRedis(StringRedisTemplate redisTemplate, String header) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token = request.getHeader(header);
        if (StringUtils.isEmpty(token)) {
            //请求头中没有，就从url中取参数
            token = request.getParameter(header);
        }
        try {
            return Long.valueOf(redisTemplate.opsForValue().get(token));
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取token剩余生命
     *
     * @param redisTemplate
     * @param header
     * @return
     */
    public static Long getTokenLifeTime(StringRedisTemplate redisTemplate, String header) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token = request.getHeader(header);
        if (!StringUtils.isEmpty(token)) {
            return redisTemplate.getExpire(token, TimeUnit.MINUTES);
        }
        return 0L;
    }

    public static String getToken(String header){
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        return request.getHeader(header);
    }
}
